package com.sunsy.authserver.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author memory
 * @date 2020/7/1
 */
@Component
public class JwtUtil {

    @Value("${jwt.token.secret}")
    private String secret;

    @Value("${jwt.token.expiration}")
    private String expiration;

    private static final String CLAIM_NAME = "token";

    public static void main(String[] args) {

    }

    public String createToken(String token) {
        return createToken(token, 0L);
    }

    public String createRefreshToken(String token) {
        return createToken(token, 7 * 24 * 3600 * 1000L);
    }

    private String createToken(String token, Long offset) {
        Date date = new Date(System.currentTimeMillis() + Long.parseLong(expiration + offset));
        //加密处理密码
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withClaim(CLAIM_NAME, token)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public Long getExpiration(String token) {
        if (token == null) {
            return -1L;
        }
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
        DecodedJWT jwt = null;
        try {
            jwt = jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            return -1L;
        }
        return (jwt.getExpiresAt().getTime() - System.currentTimeMillis()) / 1000;
    }

    public boolean verify(String token) {
        if (token == null) {
            return false;
        }
        Algorithm algorithm = Algorithm.HMAC256(secret);
        JWTVerifier jwtVerifier = JWT.require(algorithm).build();
//        .withClaim(CLAIM_NAME, username).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            return false;
        }
        return true;
    }

}
